package com.qf.autoconfig;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class MapperScannerConfigureRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //创建一个MapperScannerConfigure类型的BeanDefinition对象
//        RootBeanDefinition beanDefinition = new RootBeanDefinition(MapperScannerConfigurer.class);
//        registry.registerBeanDefinition("xx",beanDefinition);
        //上述方式，无法告诉MapperScannerConfigurer扫描那个映射接口包

        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);

        //这里的包路径需要通过用户进行配置，不可以写死

        Map<String, Object> map = importingClassMetadata.getAnnotationAttributes(EnableMapperScan.class.getName());

        String basePackage = (String) map.get("basePackage");

        builder.addPropertyValue("basePackage",basePackage);

        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();

        registry.registerBeanDefinition("xx",beanDefinition);
    }
}
